import React, {useEffect, useState} from "react";
import {TreeSelect} from "antd";
import {deleteTreeNodeById} from "@/utils/utils";
import {TreeNodeModel} from "@/global";
import {TreeSelectProps} from "antd/lib/tree-select";

/** 父节点Tree下拉选择控件属性 */
export interface TreeSelectParentProps extends TreeSelectProps<{}> {
  /** 是否新建 */
  created: boolean;
  /** 主键 */
  dataId: string;
  /** 父主键 */
  dataParentId?: string;
  /** 加载Tree数据 */
  onLoadTreeData: () => Promise<any>;
}

/**
 * 父节点Tree下拉选择控件
 * 新建时不去除当前节点以及所有下级节点,如果是编辑,则去除当前节点以及所有下级节点
 */
const TreeSelectParent = function (props: TreeSelectParentProps) {
  const {created, dataId, dataParentId, onLoadTreeData, ...rest} = props;
  const [data, setData] = useState<TreeNodeModel[]>([]);
  const expandedKeys = dataParentId ? [dataParentId] : [];

  //加载数据
  useEffect(() => {
    onLoadTreeData().then(r => {
      const tdata = r.data as TreeNodeModel[];
      if (!created && dataId && tdata && tdata.length > 0) {
        deleteTreeNodeById(tdata, dataId);
      }
      setData(tdata);
    });
  }, [created,dataId]);


  return (
    <TreeSelect
      {...rest}
      treeDefaultExpandedKeys={expandedKeys}
      treeData={data}
    />
  );
};

/** 组件默认值 */
TreeSelectParent.defaultProps = {
  treeIcon: true,
};
export default React.memo(TreeSelectParent);
